#include "net_pan.h"
#include "task_queue.h"

int net_pan_init(net_pan_t *net_pan,int workernum){
    bzero(net_pan, sizeof(net_pan_t));
    net_pan->threadnum = workernum;
    net_pan->tidArr = (pthread_t *)calloc(workernum,sizeof(pthread_t));
    net_pan->taskQueue.queueSize=0;
    net_pan->taskQueue.pFront=(task_t*)calloc(1,sizeof(task_t));
    net_pan->taskQueue.pRear=(task_t*)calloc(1,sizeof(task_t));
    net_pan->taskQueue.pFront->pNext=net_pan->taskQueue.pRear;
    pthread_mutex_init(&net_pan->taskQueue.mutex,NULL);
    pthread_cond_init(&net_pan->taskQueue.cond,NULL);
    return 0;
}

//int tcpInit(const char *ip,const char* port,int* psockfd){
//    printf("try to listen!\n");
//    struct sockaddr_in addr;
//    addr.sin_family=AF_INET;
//    addr.sin_port=htons(atoi(port));
//    addr.sin_addr.s_addr=inet_addr(ip);
//    *(psockfd)=socket(AF_INET,SOCK_STREAM,0);
//    socklen_t len=sizeof(addr);
//    int ret=bind(*psockfd,(struct sockaddr*)&addr,len);
//    ERROR_CHECK(ret,-1,"bind");
//    int reuse=1;
//    ret=setsockopt(*psockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
//    ERROR_CHECK(ret,-1,"setsockopt");
//    ret=listen(*psockfd,10);
//    ERROR_CHECK(ret,-1,"listen");
//    return 0;
//    printf("listen success!\n");
//}
//

int tcpInit(const char *ip, const char *port, int *psockfd){
    // socket setsockopt bind listen
    *psockfd = socket(AF_INET,SOCK_STREAM,0);
    int reuse = 1;
    int ret = setsockopt(*psockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
    ERROR_CHECK(ret,-1,"setsockopt");
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);
    ret = bind(*psockfd,(struct sockaddr *) &addr, sizeof(addr));
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(*psockfd,10);
    ERROR_CHECK(ret,-1,"listen");
    return 0;
}
